<script setup>
import { appStockListQuery } from "@/services/cashier";
import { onLoad, onReady, onShow, onReachBottom } from "@dcloudio/uni-app";
import { nextTick, ref, watch, onMounted } from "vue";
import { appInfo, loginSwitch } from "@/services/user";
import { chartCategory, chartProduct } from "@/services/index";
const userInfo = ref({});
onLoad((e) => {
  if (uni.getStorageSync("user")) {
    userInfo.value = uni.getStorageSync("user")
      ? JSON.parse(uni.getStorageSync("user"))
      : {};
    console.log(JSON.parse(uni.getStorageSync("user")));
  }
});

const chartCategoryList = ref([]);
const total = ref({});

const showtime = ref(false);

const selectShow = ref(false);
const selectItem = ref({ type: 1, text: "今天" });
const selectItem2 = ref({});
const timevalue = ref(Date.now());

const datePick = ref([
  {
    type: 1,
    text: "今天",
  },
  {
    type: 2,
    text: "昨天",
  },
  {
    type: 3,
    text: "近7天",
  },
  {
    type: 4,
    text: "本周",
  },
  {
    type: 5,
    text: "本月",
  },
  {
    type: 6,
    text: "上周",
  },
  {
    type: 7,
    text: "上月",
  },
]);
function open() {
  // 打开逻辑，比如设置 show 为 true
  // selectShow.value = true;
  // console.log('open');
}

onShow(() => {
  getChartCategory();
});

const sortField = ref("");
const sortOrder = ref("");
const sortFun = (str) => {
  if (sortField.value == str) {
    sortField.value = str;
    // sortOrder.value=sortOrder.value=='desc'?'asc':sortOrder.value=='desc'?'':'desc'
    if (sortOrder.value == "desc") {
      sortOrder.value = "asc";
    } else if (sortOrder.value == "asc") {
      sortOrder.value = "";
      sortField.value = "";
    } else if (sortOrder.value == "") {
      sortOrder.value = "desc";
    }
  } else {
    sortField.value = str;
    sortOrder.value = "desc";
  }
  if (selectLive.value >= 3) {
    getChartProduct(1);
  } else {
    getChartCategory(1);
  }
};

const pageIndex = ref(1);
const pageSize = ref(60);
const isgoods = ref(false);
onReachBottom(() => {
  // if (isgoods.value) {
  //   pageIndex.value = pageIndex.value + 1;
  //   getChartProduct();
  // }
});

const getChartProduct = async () => {
  isgoods.value = true;
  let data = {};
  if (selectItem.value.type) {
    data = {
      datePick: selectItem.value.type,
    };
  } else {
    if (selectItem2.value.type == 4) {
      data = {
        startTime: timevalue.value + " 00:00:00",
        endTime: timevalue.value + " 23:59:59",
      };
    } else {
      data = {
        datePick: selectItem2.value.type,
      };
    }
  }
  data.sortField = sortField.value;
  data.sortOrder = sortOrder.value;
  data.shopId = userInfo.value.shopId;

  data.categoryId = selectCategoryID.value;
  data.pageSize = pageSize.value;
  data.pageIndex = pageIndex.value;
  console.log(parentIdLst.value);

  const res = await chartProduct(data);
  chartCategoryList.value = res.data.data;
  total.value = res.data.total;
};

const getChartCategory = async () => {
  isgoods.value = false;
  pageIndex.value = 1;

  let data = {};
  if (selectItem.value.type) {
    data = {
      datePick: selectItem.value.type,
    };
  } else {
    if (selectItem2.value.type == 4) {
      data = {
        startTime: timevalue.value + " 00:00:00",
        endTime: timevalue2.value + " 23:59:59",
      };
    } else {
      data = {
        datePick: selectItem2.value.type,
      };
    }
  }
  data.sortField = sortField.value;
  data.sortOrder = sortOrder.value;
  data.shopId = userInfo.value.shopId;

  if (selectLive.value > 0 && selectLive.value <= 2) {
    data.parentId = parentIdLst.value[selectLive.value].id;
  }
  console.log(parentIdLst.value[selectLive.value].id);

  const res = await chartCategory(data);
  chartCategoryList.value = res.data.data;
  total.value = res.data.total;
};

const selectItemFun = (item, index) => {
  console.log("selectItemFun", item, index);
  if (index == 1) {
    selectItem2.value = {};
    selectItem.value = item;
    selectShow.value = false;
    // getChartBusiness();
    selectLive.value = 0;
    getChartCategory();

    // getChartProduct();
  } else {
    if (item.type == 4) {
      // showtime.value = true;
      // selectShow.value = false;
      // selectItem.value = item;
      selectItem.value = {};
      selectItem2.value = item;
    } else {
      selectItem.value = {};
      selectItem2.value = item;
      selectShow.value = false;

      selectLive.value = 0;
      getChartCategory();
    }
  }
};
const datetimePickerRef = ref(null);

onReady(() => {
  // 微信小程序需要用此写法
  datetimePickerRef.value.setFormatter(formatter);
});
const formatter = (type, value) => {
  if (type === "year") {
    return `${value}年`;
  }
  if (type === "month") {
    return `${value}月`;
  }
  if (type === "day") {
    return `${value}日`;
  }
  return value;
};
const confirmDate = (e) => {
  let dateobj = new Date(e.value);

  if (showtime.value == true) {
    minTime.value = e.value;
    timevalue.value =
      dateobj.getFullYear() +
      "-" +
      (dateobj.getMonth() + 1 < 10
        ? "0" + (dateobj.getMonth() + 1)
        : dateobj.getMonth() + 1) +
      "-" +
      (dateobj.getDate() < 10 ? "0" + dateobj.getDate() : dateobj.getDate());
    selectItem.value = {};
    selectItem2.value = { type: 4, text: timevalue.value };
    showtime.value = false;
    selectShow.value = false;
    showtime2.value = true;
    // getChartBusiness();
    selectLive.value = 0;
    return;
  }

  if (showtime2.value == true) {
    timevalue2.value =
      dateobj.getFullYear() +
      "-" +
      (dateobj.getMonth() + 1 < 10
        ? "0" + (dateobj.getMonth() + 1)
        : dateobj.getMonth() + 1) +
      "-" +
      (dateobj.getDate() < 10 ? "0" + dateobj.getDate() : dateobj.getDate());
    selectItem.value = {};
    selectItem2.value = { type: 4, text: timevalue.value };
    showtime2.value = false;
    selectShow.value = false;

    // getChartBusiness();
    selectLive.value = 0;
    // selectShow.value = true;
    getChartCategory();
  }

  // getChartProduct();
};

const parentIdLst = ref([{ name: "一级分类", id: "" }]);

const selectLive = ref(0);
const showLive = ref(false);
const selectGidFun = (item, index) => {
  selectLive.value = index;
  console.log(item, index);
  showLive.value = false;
  getChartCategory();
};
const selectCategoryID = ref("");
const selectCategory = (item) => {
  selectCategoryID.value = item.categoryId;
  if (selectLive.value > 2) {
    return;
  }

  if (selectLive.value == 0) {
    if (parentIdLst.value[selectLive.value + 1]) {
      parentIdLst.value[selectLive.value + 1] = {
        name: "二级分类",
        id: item.categoryId,
      };
    } else {
      parentIdLst.value.push({
        name: "二级分类",
        id: item.categoryId,
      });
    }
  }
  if (selectLive.value == 1) {
    if (parentIdLst.value[selectLive.value + 1]) {
      parentIdLst.value[selectLive.value + 1] = {
        name: "三级分类",
        id: item.categoryId,
      };
    } else {
      parentIdLst.value.push({
        name: "三级分类",
        id: item.categoryId,
      });
    }
  }

  selectLive.value = selectLive.value + 1;
  if (selectLive.value >= 3) {
    getChartProduct();
  } else {
    getChartCategory();
  }
};

//区间选择
const showtime2 = ref(false);
const timevalue2 = ref(Date.now());
const minTime = ref(Date.now());

const Time = (e) => {
  const date = new Date(e);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

//无网状态
const connected = () => {
  getChartCategory();
};
</script>

<template>
  <view class="bg">
    <up-navbar
      bgColor="#ffffff"
      @rightClick="rightClick"
      :autoBack="true"
      :safeAreaInsetTop="true"
      :fixed="true"
      :placeholder="true"
      :leftText="'返回'"
    >
      <template #right> </template>
      <template #center>
        <text
          class="text-white"
          style="
            font-weight: 500;
            font-size: 34rpx;
            color: #000000;
            line-height: 48rpx;
            text-align: center;
          "
          >销售统计</text
        ></template
      >
    </up-navbar>

    <view class="content">
      <view class="top">
        <view
          class="top-item"
          :class="{ 'top-item-select': selectItem.type == 1 }"
          @click="selectItemFun({ type: 1, text: '今日' }, 1)"
          >今日
        </view>
        <view
          class="top-item"
          :class="{ 'top-item-select': selectItem.type == 4 }"
          @click="selectItemFun({ type: 4, text: '本周' }, 1)"
          >本周
        </view>
        <view
          class="top-item"
          :class="{ 'top-item-select': selectItem.type == 5 }"
          @click="selectItemFun({ type: 5, text: '本月' }, 1)"
          >本月
        </view>
        <view
          class="top-item"
          :class="{
            'top-item-select':
              selectItem.type != 5 &&
              selectItem.type != 4 &&
              selectItem.type != 1,
          }"
          @click="selectShow = true"
          >更多<up-icon
            name="arrow-right"
            color="#8C8C8C"
            size="24rpx"
            style="margin-top: 0rpx"
          ></up-icon
        ></view>
      </view>
      <view class="info-hx"></view>
      <view class="info">
        <view class="info-item-top">
          <text>总计 </text>销售订单<text class="bc_color">{{
            total.orderCount
          }}</text
          >单 销售金额<text class="bc_color">{{ total.salesAmount }}</text
          >元
        </view>
        <view class="info-item info-item-title">
          <view class="one" @click="showLive = !showLive"
            ><text
              >{{
                selectLive == 0
                  ? "一级分类"
                  : selectLive == 1
                  ? "二级分类"
                  : selectLive == 2
                  ? "三级分类"
                  : "商品名称"
              }}
            </text>
            <view
              ><up-icon
                :class="showLive ? 'show_live' : 'no_show_live'"
                name="play-right-fill"
                color="#2979ff"
                size="20rpx"
              ></up-icon>
            </view>

            <view class="selectOrder" v-if="showLive" @click.stop>
              <view class="selectOrder-jt"><view></view></view>
              <view
                class="selectOrder-item"
                @click="selectGidFun(item, index)"
                v-for="(item, index) in parentIdLst"
                :key="index"
                >{{ item.name }}</view
              >
              <!-- <view class="selectOrder-item">二级分类</view>
              <view class="selectOrder-item">三级分类</view> -->
            </view></view
          >
          <view class="two">
            <view class="shure" @click="sortFun('orderNum')"
              ><text>销售订单</text>
              <view class="shure-icon">
                <up-icon
                  class="play-left-fill"
                  name="play-left-fill"
                  :color="
                    sortField == 'orderNum' && sortOrder == 'asc'
                      ? '#2979ff'
                      : '#C9CDD4'
                  "
                  size="18rpx"
                ></up-icon>
                <up-icon
                  class="play-right-fill"
                  name="play-right-fill"
                  :color="
                    sortField == 'orderNum' && sortOrder == 'desc'
                      ? '#2979ff'
                      : '#C9CDD4'
                  "
                  size="18rpx"
                ></up-icon>
              </view>
            </view>
          </view>
          <view class="three">
            <view
              class="shure"
              style="justify-content: flex-end; padding-right: 10rpx"
              @click="sortFun('salesAmount')"
              ><text>销售金额</text>
              <view class="shure-icon">
                <up-icon
                  class="play-left-fill"
                  name="play-left-fill"
                  :color="
                    sortField == 'salesAmount' && sortOrder == 'asc'
                      ? '#2979ff'
                      : '#C9CDD4'
                  "
                  size="18rpx"
                ></up-icon>
                <up-icon
                  class="play-right-fill"
                  name="play-right-fill"
                  :color="
                    sortField == 'salesAmount' && sortOrder == 'desc'
                      ? '#2979ff'
                      : '#C9CDD4'
                  "
                  size="18rpx"
                ></up-icon>
              </view>
            </view>
          </view>
        </view>
        <view
          class="info-item"
          v-for="(item, index) in chartCategoryList && chartCategoryList.data
            ? chartCategoryList.data
            : chartCategoryList"
          :key="index"
          @click="selectCategory(item)"
        >
          <view class="one">
            {{ item.categoryName ? item.categoryName : item.productName }}
          </view>
          <view class="two" style="text-align: center">
            {{ item.orderCount }}
          </view>
          <view class="three" style="text-align: right; margin-right: 10rpx">
            ¥{{ item.salesAmount }}
          </view>
        </view>
        <no-Data
          style="padding-bottom: 200rpx; margin-top: 10rpx"
          text="暂无数据"
          v-if="
            (chartCategoryList &&
              chartCategoryList.data &&
              chartCategoryList.data.length <= 0) ||
            chartCategoryList.length <= 0
          "
        ></no-Data>
      </view>
    </view>
  </view>

  <up-datetime-picker
    title="开始时间"
    class="top-center"
    ref="datetimePickerRef"
    :hasInput="false"
    @close="showtime = false"
    @confirm="confirmDate"
    @cancel="showtime = false"
    format="YYYY-MM-DD"
    :show="showtime"
    v-model="timevalue"
    :formatter="formatter"
    :closeOnClickOverlay="true"
    mode="date"
  >
  </up-datetime-picker>

  <up-datetime-picker
    class="top-center"
    title="结束时间"
    ref="datetimePickerRef"
    :hasInput="false"
    @close="showtime2 = false"
    @confirm="confirmDate"
    @cancel="showtime2 = false"
    format="YYYY-MM-DD"
    :show="showtime2"
    v-model="timevalue2"
    :formatter="formatter"
    :closeOnClickOverlay="true"
    :minDate="minTime"
    mode="date"
  >
  </up-datetime-picker>

  <up-popup
    :closeable="true"
    :show="selectShow"
    @close="selectShow = false"
    :safeAreaInsetBottom="true"
    @open="open"
    round="15"
  >
    <view class="popup-content">
      <view class="popup-content-title" @click="showtime = false">取消</view>
      <view class="popup-content-selTop">快捷选择</view>
      <view class="kj-select">
        <view
          class="kj-select-item"
          :class="selectItem.type == item.type ? 'kj-select-item-seleect' : ''"
          v-for="(item, index) in datePick"
          :key="index"
          @click="selectItemFun(item, 1)"
        >
          {{ item.text }}
        </view>
      </view>
      <view class="popup-content-selTop">自定义</view>
      <view class="kj-select">
        <view
          class="kj-select-item"
          :class="selectItem2.type == 1 ? 'kj-select-item-seleect' : ''"
          @click="selectItemFun({ type: 1, text: '今日' }, 2)"
        >
          今日
        </view>
        <view
          class="kj-select-item"
          :class="selectItem2.type == 2 ? 'kj-select-item-seleect' : ''"
          @click="selectItemFun({ type: 2, text: '昨日' }, 2)"
          >昨日
        </view>
        <view
          class="kj-select-item"
          :class="selectItem2.type == 3 ? 'kj-select-item-seleect' : ''"
          @click="selectItemFun({ type: 3, text: '近7日' }, 2)"
        >
          近7日
        </view>
        <view
          class="kj-select-item"
          :class="selectItem2.type == 4 ? 'kj-select-item-seleect' : ''"
          @click="selectItemFun({ type: 4, text: '自定义' }, 2)"
        >
          自定义
        </view>
      </view>
      <view class="kj-select" v-if="selectItem2.type == 4">
        <view
          class="kj-select-item kj-select-item2"
          :class="showtime ? 'kj-select-item-seleect' : ''"
          @click="
            showtime = true;
            selectShow = false;
          "
        >
          {{ Time(timevalue) }}
        </view>
        <view>-</view>
        <view
          class="kj-select-item kj-select-item2"
          :class="showtime2 ? 'kj-select-item-seleect' : ''"
          @click="
            showtime2 = true;
            selectShow = false;
          "
          >{{ Time(timevalue2) }}
        </view>
      </view>

      <view class="bt-text"> 报表统计时间:0:00-次日0:00</view>
    </view>
  </up-popup>
  <noWork @connected="connected"> </noWork>
</template>

<style lang="scss" scoped>
@import "index.scss";
</style>
